package com.atguigu.thread;

public class Test1 {

    public static void main(String[] args) {
        Mathutil mathutil1 = new Mathutil();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    mathutil1.increament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    mathutil1.decreament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    mathutil1.increament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                    mathutil1.decreament();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class Mathutil{
    public int i = 0;
    public synchronized void increament() throws InterruptedException {
        while (i != 0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() +"  " + ++i);
        this.notify();
    }

    public synchronized void decreament() throws InterruptedException {
        while (i==0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() + "  " + --i);
        this.notify();
    }
}